<?php

namespace app\admin\controller\wdsxh;

use addons\wdsxh\library\Wxapp;
use app\admin\model\wdsxh\Order;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;

/**
 * 入会申请
 *
 * @icon fa fa-circle-o
 */
class MemberProfile extends Backend
{

    /**
     * MemberProfile模型对象
     * @var \app\admin\model\wdsxh\MemberProfile
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wdsxh\MemberProfile;
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row){
                $row->user;
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);

        $this->view->assign("content", json_decode($row->content,true));
        $this->view->assign("user", $row->user);

        return $this->view->fetch();
    }
    public function pass($ids){
        $row = $this->model->get($ids);
        if($this->request->isPost()){
            $fill_company = 0;
            $company_name = '';
            // 会员头像
            $member_avatar = '/assets/addons/wdsxh/img/default.png';
            // 公司职务
            $company_post = '';
            // 籍贯
            $birthplace = '';
            // 会员简介
            $selfinstroduce = '';
            // 行业分类
            $member_unit_cat_id = '';
            // 公司简介
            $company_brief = '';
            // 公司地址
            $company_address = '';
            $company_address_detail = '';
            $company_address_lat = '';
            $company_address_lng = '';
            // 公司网址
            $company_site = '';
            $content_array = json_decode($row['content'],true);
            foreach($content_array as $k=>$v) {
                if(isset($v['value']) && !empty($v['value'])){
                    if($v['field'] == 'company') {
                        $company_name = $v['value'];
                    }
                    if($v['field'] == 'avatar') {
                        $member_avatar = $v['value'];
                    }
                    if($v['field'] == 'position') {
                        $company_post = $v['value'];
                    }
                    if($v['field'] == 'address') {
                        $birthplace = str_replace('省','省/',$v['value']);
                    }
                    if($v['field'] == 'selfinstroduce') {
                        $selfinstroduce = $v['value'];
                    }
                    if($v['field'] == 'type') {
                        $member_unit_cat = model('app\admin\model\wdsxh\MemberUnitCat')->where(['name' => ['like','%'.$v['value'].'%']])->value('id');
                        if($member_unit_cat > 0) {
                            $member_unit_cat_id = $member_unit_cat;
                        }
                    }

                    if($v['field'] == 'instroduce') {
                        $company_brief = $v['value'];
                    }
                    if($v['field'] == 'companyaddress') {
                        $company_address_detail = $v['value'];
                        $lat_lng = getTXLatLng($company_address_detail);
                        if(!empty($lat_lng)){
                            $company_address_detail = str_replace($lat_lng['address_components']['province'],'',$company_address_detail);
                            $company_address_detail = str_replace($lat_lng['address_components']['city'],'',$company_address_detail);
                            $company_address_detail = str_replace($lat_lng['address_components']['district'],'',$company_address_detail);
                            $company_address = "{$lat_lng['address_components']['province']}/{$lat_lng['address_components']['city']}/{$lat_lng['address_components']['district']}";
                            $company_address_lat = $lat_lng['location']['lat'];
                            $company_address_lng = $lat_lng['location']['lng'];
                        }

                    }
                    if($v['field'] == 'companyweb') {
                        $company_site = $v['value'];
                    }
                }
            }
            $params = $this->request->post("row/a");
            $level=\app\admin\model\wdsxh\MemberUnitLevel::get($params['level_id']);
            if(!$level){
                $this->error('会员级别信息错误');
            }
            if($level['is_company'] == '1') {
                $fill_company = 1;
            }
            $expense=floatval($level->expense);
            $member=\app\admin\model\wdsxh\Member::where('uid',$row->uid)->find();
            if($member){
                $member->uid=$row->uid;
                $member['name']=$row['name'];
                $member->mobile=$row->mobile;
                $member->level_id=$params['level_id'];
                $member->jointime=$expense > 0?date('Y-m-d'):$level['jointime'];
                $member->expiretime=$expense > 0?date('Y-m-d'):$level['expiretime'];
                $member->status = 1;

                $member->picture = $member_avatar;
                $member->company_post = $company_post;
                $member->birthplace = $birthplace;
                $member->introduction = $selfinstroduce;

                $res=$member->save();
            }else{
                $data=array(
                    'uid'=>$row->uid,
                    'name'=>$row['name'],
                    'mobile'=>$row->mobile,
                    'picture'=>$member_avatar,
                    'level_id'=>$params['level_id'],
                    'jointime'=>$expense > 0?date('Y-m-d'):$level['jointime'],
                    'expiretime'=>$expense > 0?date('Y-m-d'):$level['expiretime'],
                    'status'=>'1',

                    'company_post'=>$company_post,
                    'birthplace'=>$birthplace,
                    'introduction'=>$selfinstroduce,
                );
                $res=\app\admin\model\wdsxh\Member::create($data);
            }
            $memberUnitLevelObj = (new \app\admin\model\wdsxh\MemberUnitLevel())->get($params['level_id']);
            if($res){
                $row->status='1';
                $row->save();
                if($res === 1){
                    $res = $member;
                }
                if($res->status == '1' || ($expense > 0)){
                    $Coceral=wdsxh_get_coceral();
                    if($memberUnitLevelObj['expense'] == 0.00) {
                        $money = (new \app\admin\model\wdsxh\MemberUnitLevel())->where('id',$params['level_id'])->value('expense');
                        $orderData=array(
                            'uid'=>$row->uid,
                            'items_id'=>$res->id,
                            'type'=>2,
                            'order_sn'=>wdsxh_create_order(),
                            'money'=>$money,
                            'status'=>'2',
                            'createtime'=>time(),
                            'paytime'=>time(),
                        );
                        Order::create($orderData);
                        $thing1_value = '恭喜您，您已成功加入'.$Coceral['name'];
                        $path = '/pages/Personal/index';
                    } else {
                        $thing1_value = '通过审核，请前往小程序缴纳会费！';
                        $path = '/pages/Component/Module/Payment/Program/pay/index/index';
                    }
                    //入会申请成功通知
                    $Coceral=wdsxh_get_coceral();
                    try{
                        $conf = (new \app\admin\model\wdsxh\Config())->where('id',1)->find();
                        $data=[
                            'thing3'=>[
                                'value'=>$Coceral['name'],
                            ],
                            'time2'=>[
                                'value'=>date('Y-m-d H:i:s'),
                            ],
                            'thing1'=>[
                                'value'=>$thing1_value,
                            ]
                        ];
                        $result = Wxapp::subscribeMessage($conf['initiation_success'],trim(wdsxh_get_openid($row->uid)),$path,$data);
                    }catch (\think\Exception $e){
//                        $this->error($e->getMessage());
                    }
                }

                if($fill_company && ($memberUnitLevelObj['expense'] == 0.00)) {
                    $member_unit_data=array(
                        'level_id'=>$params['level_id'],
                        'member_id'=>$res->id,
                        'company_name'=>$company_name,
                        'status'=>'1',
                        'cat_id' => $member_unit_cat_id,
                        'company_brief' => $company_brief,
                        'company_address' => $company_address,
                        'company_address_detail' => $company_address_detail,
                        'company_address_lat' => $company_address_lat,
                        'company_address_lng' => $company_address_lng,
                        'company_site' => $company_site,
                        'createtime'=>time(),
                    );
                    \app\admin\model\wdsxh\MemberUnit::create($member_unit_data);
                }
                $business = [
                    'uid'=>$res->id,
                    'status'=>'1',
                ];
                $user_id = $row->uid;
                \app\admin\model\wdsxh\Business::where('user_id',$user_id)->update($business);

                if($memberUnitLevelObj['expense'] == 0.00) {
                    //入会审核成功通知
                    try{
                        $conf=(new \app\admin\model\wdsxh\Config())->where('id',1)->find();
                        $data=[
                            'thing1'=>[
                                'value'=>$row['name'],
                            ],
                            'time3'=>[
                                'value'=>date('Y-m-d H:i:s'),
                            ],
                            'phrase4'=>[
                                'value'=>'审核通过',
                            ],
                            'thing5'=>[
                                'value'=>'恭喜成功加入会员',
                            ],
                        ];
                        $result = Wxapp::subscribeMessage($conf['initiation_audit'],trim(wdsxh_get_openid($row->uid)),'/pages/Personal/index',$data);
                    }catch (\think\Exception $e){
//                        $this->error($e->getMessage());
                    }
                }

                $this->success('操作成功！');
            }
            $this->error('发生未知错误');
        }
        return $this->view->fetch();
    }
    public function refuse($ids){
        $row = $this->model->get($ids);
        if($this->request->isPost()){
            $params = $this->request->post("row/a");
            $row->reason=$params['reason'];
            $row->status='2';
            $row->save();

            //入会审核成功通知
            try{
                $conf = (new \app\admin\model\wdsxh\Config())->where('id',1)->find();
                $data=[
                    'thing1'=>[
                        'value'=>$row['name'],
                    ],
                    'time3'=>[
                        'value'=>date('Y-m-d H:i:s'),
                    ],
                    'phrase4'=>[
                        'value'=>'审核未通过',
                    ],
                    'thing5'=>[
                        'value'=>'原因：'.$params['reason'],
                    ],
                ];
                Wxapp::subscribeMessage($conf['initiation_audit'],trim(wdsxh_get_openid($row->uid)),'/pages/Component/Module/Main/Program/apply/index/index',$data);
            }catch (\think\Exception $e){
            }

            $this->success();
        }
        return $this->view->fetch();
    }

    public function action($state=0,$ids=''){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->status=$state?'1':'2';
        try{
            if($state == 1){
                $member=\app\admin\model\wdsxh\Member::where('uid',$row->uid)->find();
                if($member){
                    throw new Exception('该用户已经是会员了！');
                }
                $data=array(
                    'uid'=>$row->uid,
                    'name'=>$row['name'],
                    'mobile'=>$row->mobile,
                    'level_id'=>$this->getMemberMinLevel(),
                    'jointime'=>date('Y-m-d'),
                    'expiretime'=>date('Y-m-d'),
                );
                \app\admin\model\wdsxh\Member::create($data);
            }
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $row->save();
        $this->success('操作成功！');
    }

    private function getMemberMinLevel(){
        $level=\app\admin\model\wdsxh\MemberUnitLevel::order('weigh desc')->field('id')->find();
        return $level['id'];
    }

    public function fieldset(){
        if($this->request->isPost()){
            $params=$this->request->param('row/a');
            if(empty($params['field']) || !is_array($params['field'])){
                $this->error('字段信息不能为空');
            }
            $temp=array();
            foreach ($params['field'] as $row){
                $temp[]=$row;
            }
            $field_array = array_column($temp,'field');
            if (count($field_array) != count(array_unique($field_array))) {
                $this->error('字段名不能重复');
            }
            config('fieldset',$temp);
            file_put_contents(
                ADDON_PATH . "wdsxh" . DS . 'config' . DS . "fieldset.php",
                '<?php' . "\n\nreturn " . var_export_short($temp) . ";\n"
            );
            $this->success('操作成功！');
        }
        $config_file = ADDON_PATH . "wdsxh" . DS . 'config' . DS . "fieldset.php";
        if (is_file($config_file)) {
            $fidldset = include $config_file;
        }
        if(empty($fidldset)){
            $fidldset=array (
                0 =>
                    array (
                        'type' => 'text',
                        'label' => '真实姓名',
                        'field' => 'name',
                        'option' => '请输入你的真实姓名',
                    ),
                1 =>
                    array (
                        'type' => 'number',
                        'label' => '联系电话',
                        'field' => 'mobile',
                        'option' => '请输入你的联系电话',
                    ),
                2 =>
                    array (
                        'type' => 'radio',
                        'label' => '性别',
                        'field' => 'gender',
                        'option' => '男,女',
                    ),
            );
        }
        $this->assign('fieldset',json_encode($fidldset));
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            $param['status'] = '3';
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    \app\admin\model\wdsxh\Member::where('uid',$v->uid)->delete();
                    \app\admin\model\wdsxh\Business::where('user_id',$v->uid)->update($param);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
